from common.common_driver import get_page
from utils.project_path import ProjectPath
from utils.read_yaml import get_yaml_data
from utils.handle_log import log


class BasePage(object):
    def __init__(self):
        self.page = get_page()
        # 根据类名，获取放在yaml文件的元素
        self.locators = get_yaml_data(ProjectPath.configs_path / 'common_elements.yaml').get(self.__class__.__name__,
                                                                                             "未找到类名，请检查")
        # 通过setattr，动态的将元素定位设置类变量
        # 实例直接调用会有警告，可通过__getitem__规避
        for key, value in self.locators.items():
            setattr(self, key, value)

    # 其子类实例化后，可通过self['username']获取元素定位，如LoginPage
    def __getitem__(self, item):
        return self.locators[item]

    def open_url(self, url):
        log.info(f"打开url: {url}")
        self.page.goto(url)

    def get_element(self, locator):
        return self.page.locator(locator)

    def input_text(self, locator, text):
        log.info(f"定位元素: {locator}，并输入文本: {text}")
        self.get_element(locator).fill(text)

    def click_element(self, locator):
        log.info(f"定位元素: {locator}，并点击")
        self.get_element(locator).click()

    def get_element_text(self, locator):
        log.info(f"定位元素: {locator}，并获取文本")
        return self.get_element(locator).text_content()
